<script setup lang="ts">
definePageConfig({
  navigationBarTitleText: '手机号验证'
});

import { ref, reactive, onMounted, watch, computed, onUnmounted } from 'vue';
import { useToast } from '@/composables';
import Taro from '@tarojs/taro';
import { sendSmsCode, verifyPhone, getCaptcha, verifyCaptcha } from '@/service/api/auth';
import { useAuthStore } from '@/store';

const userStore = useAuthStore();

const toast = useToast();
const objs = JSON.parse(Taro.getStorageSync('openid') || '{}');

console.log("Taro.getStorageSync('openid')", objs.value)

const form = reactive({
  phone: userStore.nurseUser.phone || '',
  code: '',
  captchaCode: '' // 图形验证码
});

const formRef = ref<any>(null);
const countdown = ref(0);
const isCounting = computed(() => countdown.value > 0);
const btnText = computed(() => isCounting.value ? `${countdown.value}s后重新发送` : '获取验证码');
const showTips = ref(false);
let timer: number | null = null;

// 图形验证码相关状态
const captchaUrl = ref('');
const captchaLoading = ref(false);
const showCaptchaModal = ref(false);
const captchaUUID = ref(''); // 存储图形验证码的UUID

const textClass = computed(() => {
    return 'some-class'
})

// 清理定时器
const clearTimer = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

// 获取图形验证码
const fetchCaptcha = async () => {
  captchaLoading.value = true;
  try {
    const res = await getCaptcha();
    if (res.success) {
      captchaUrl.value = res.success.imageUrl;
      captchaUUID.value = res.success.uuid;
    } else {
      toast.error(res.error?.message || '获取图形验证码失败');
    }
  } catch (error: any) {
    console.error('获取图形验证码失败', error);
    toast.error('获取图形验证码失败，请重试');
  } finally {
    captchaLoading.value = false;
  }
};

// 刷新图形验证码
const refreshCaptcha = () => {
  form.captchaCode = '';
  captchaUUID.value = '';
  fetchCaptcha();
};

// 验证图形验证码
const validateCaptcha = async (): Promise<boolean> => {
  if (!form.captchaCode) {
    toast.error('请输入图形验证码');
    return false;
  }
  
  if (!captchaUUID.value) {
    toast.error('验证码已过期，请重新获取');
    refreshCaptcha();
    return false;
  }
  
  try {
    const res = await verifyCaptcha(form.captchaCode, captchaUUID.value, form.phone);
    if (res.success) {
      return true;
    } else {
      toast.error(res.error?.message || '图形验证码错误');
      refreshCaptcha();
      return false;
    }
  } catch (error: any) {
    toast.error('验证图形验证码失败');
    refreshCaptcha();
    return false;
  }
};

// 发送验证码
const getCode = async () => {
  if (isCounting.value) return;

  // 简单检查手机号格式
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    toast.error('请输入正确的手机号');
    return;
  }

  // 显示图形验证码弹窗
  showCaptchaModal.value = true;
  if (!captchaUrl.value) {
    await fetchCaptcha();
  }
};

// 确认发送短信验证码
const confirmSendSmsCode = async () => {
  // 验证图形验证码
  const isValidCaptcha = await validateCaptcha();
  if (!isValidCaptcha) {
    return;
  }

  try {
    showCaptchaModal.value = false;
    showTips.value = true;
    countdown.value = 60;
    
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearTimer();
      }
    }, 1000) as unknown as number;
    
    // const res = await sendSmsCode(form.phone);
    // console.log("res 1110", res)
    // if (res.success) {
    //   toast.success('验证码已发送');
    // } else {
    //   clearTimer();
    //   countdown.value = 0;
    //   toast.error(res.error?.message || res.success?.message || '验证码发送失败');
    // }
  } catch (error: any) {
    console.log('Phone validation failed:', error);
  }
};

// 提交验证
const submitForm = async () => {
  // 简单检查
  if (!form.phone) {
    toast.error('请输入手机号');
    return;
  }
  if (!form.code) {
    toast.error('请输入验证码');
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    toast.error('请输入正确的手机号');
    return;
  }
  if (form.code.length !== 6) {
    toast.error('请输入6位验证码');
    return;
  }

  try {
    toast.loading('验证中...');
    const openid = objs.value;
    const res = await verifyPhone(form.phone, form.code, openid);
    console.log("res 222", res)
    
    if (res.success) {
      toast.success('验证成功');
      showTips.value = false;
      userStore.nurseUser.isPhone = '1';
      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    } else {
      toast.error(res.error?.message || res.success?.message || '验证失败，请检查信息');
    }
  } catch (error: any) {
    console.log('Form validation failed:', error);
  }
};

// 手机号脱敏处理
const formatPhone = (phone: string) => {
  if (!phone || phone.length !== 11) return phone;
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};

// 组件卸载时清理定时器
onUnmounted(() => {
  clearTimer();
});
</script>

<template>
  <basic-layout>
    <view class="bg-white min-h-screen p-4">
      <!-- 提示信息 - 新增showTips控制显示 -->
      <view class="bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r my-4" v-if="showTips">
        <view class="flex items-start">
          <view class="i-local-info-circle text-blue-500 mt-0.5"></view>
          <view class="ml-2 text-sm" :class="textClass">
            <text v-if="!form.phone" class="text-blue-700">
              验证码将发送至您的手机，请注意查收
            </text>
            <text v-else-if="isCounting" class="text-blue-700">
              验证码已发送至 <text class="font-medium">{{ formatPhone(form.phone) }}</text>，{{ countdown }}秒后可重新发送
            </text>
            <text v-else class="text-blue-700">
              验证码已发送至 <text class="font-medium">{{ formatPhone(form.phone) }}</text>，请查收后输入
            </text>
          </view>
        </view>
      </view>
      
      <!-- 表单 -->
      <nut-form ref="formRef" :model="form">
        <nut-form-item label="手机号" prop="phone">
          <nut-input 
            v-model="form.phone" 
            placeholder="请输入11位手机号"
            type="number"
            maxlength="11"
          />
        </nut-form-item>
        
        <nut-form-item label="验证码" prop="code">
          <view class="flex items-center">
            <nut-input 
              v-model="form.code" 
              placeholder="请输入6位验证码"
              type="number"
              maxlength="6"
              class="flex-1"
            />
            <nut-button 
              :type="isCounting ? 'default' : 'primary'" 
              :disabled="isCounting"
              @click="getCode"
              size="small"
              class="ml-2"
            >
              {{ btnText }}
            </nut-button>
          </view>
        </nut-form-item>
        
        <!-- 确认按钮 -->
        <view class="mt-6">
          <nut-button 
            type="primary" 
            size="large" 
            @click="submitForm"
            :disabled="!form.phone || !form.code"
            class="w-full"
          >
            确认提交
          </nut-button>
        </view>
      </nut-form>
      
      <!-- 隐私政策 -->
      <view class="mt-4 text-center text-xs text-gray-500">
        <text>点击"确认提交"，即表示您同意</text>
        <text class="text-blue-500">《短信服务条款》</text>
        <text class="text-blue-500">《隐私政策》</text>
      </view>
    </view>

    <!-- 图形验证码弹窗 -->
    <nut-popup 
      v-model:visible="showCaptchaModal" 
      position="center" 
      :style="{ width: '80%', maxWidth: '600rpx' }"
      round
    >
      <view class="p-6">
        <view class="text-center mb-4">
          <text class="text-[32rpx] font-bold">图形验证码</text>
        </view>
        
        <!-- 图形验证码图片 -->
        <view class="flex justify-center mb-4">
          <view v-if="captchaLoading" class="flex items-center justify-center w-[200rpx] h-[80rpx] bg-gray-100 rounded">
            <text class="text-gray-500">加载中...</text>
          </view>
          <image 
            v-else-if="captchaUrl" 
            :src="captchaUrl" 
            class="w-[200rpx] h-[80rpx] border border-gray-200 rounded cursor-pointer"
            @click="refreshCaptcha"
            mode="aspectFit"
          />
          <view v-else class="flex items-center justify-center w-[200rpx] h-[80rpx] bg-gray-100 rounded">
            <text class="text-gray-500">验证码加载失败</text>
          </view>
        </view>
        
        <!-- 刷新按钮 -->
        <view class="text-center mb-4">
          <nut-button 
            type="default" 
            size="small" 
            @click="refreshCaptcha"
            :disabled="captchaLoading"
          >
            <view class="flex items-center">
              <view class="i-local-refresh mr-1"></view>
              刷新验证码
            </view>
          </nut-button>
        </view>
        
        <!-- 验证码输入框 -->
        <view class="mb-6">
          <nut-input 
            v-model="form.captchaCode" 
            placeholder="请输入图形验证码"
            maxlength="4"
            class="text-center text-[28rpx]"
          />
        </view>
        
        <!-- 操作按钮 -->
        <view class="flex gap-3">
          <nut-button 
            type="default" 
            size="large" 
            @click="showCaptchaModal = false"
            class="flex-1"
          >
            取消
          </nut-button>
          <nut-button 
            type="primary" 
            size="large" 
            @click="confirmSendSmsCode"
            :disabled="!form.captchaCode"
            class="flex-1"
          >
            确认发送
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </basic-layout>
</template>    